import React from 'react';
import './App.css'
import Header from './components/Header/Header'
import Footer from './components/Footer/Footer'
import List from './components/List/List'


class App extends React.Component{
  // 每条task
  state = {todos: [
    {id: 1, name: 'eating', done: false},
    {id: 2, name: 'sleeping', done: true}
  ]}
  // Header组件操作App组件，添加一条task
  addTodo = (todoObj)=>{
    // this.state.todos.unshift(todoObj)
    const todos = [todoObj, ...this.state.todos]
    this.setState({todos: todos})
  }
  // Item组件操作App组件，修改done
  changeDone = (id,done)=>{
    const {todos} = this.state
    // 遍历task，找到对应id的task，修改其done
    const newTodos = todos.map((item)=>{
      if(item.id === id){
        // done=done 可以简写为done
        return {...item, done}
      }else{
        return item
      }
    })
    this.setState({todos: newTodos})
  }
  // 删除一条task
  handleDelete = (id)=>{
    console.log("已完成的任务id：",id)
    const {todos} = this.state
    // 遍历task，找到对应id的task，删除之
    const newTodos = todos.filter((todosObj)=>{
      return todosObj.id !== id
    })
    this.setState({todos: newTodos})
  }
  // 删除已完成tasks
  deleteSome = ()=>{
    const {todos} = this.state
    const newTodos = todos.filter((todosObj)=>{
      return todosObj.done !== true
    })
    this.setState({todos: newTodos})
  }
  // 全选/取消全选任务
  handleChangeAll = (flag)=>{
    const {todos} = this.state
    todos.forEach((item)=>{
      item.done = flag
    })
    this.setState({todos:todos})
  }
  
  render(){
    return (
      <div className="todo-container">
        <div className="todo-wrap">
          <Header addTodo={this.addTodo} {...this.state}/>
          <List {...this.state} changeDone={this.changeDone} handleDelete={this.handleDelete}/>
          <Footer {...this.state} deleteSome={this.deleteSome} handleChangeAll={this.handleChangeAll}/>
        </div>
      </div>
    );
  }
}

export default App;
